import Vue from 'vue'

const state = {
  mode: localStorage.getItem('mode') ?? 'backend',
  dataTypeMap: JSON.parse(localStorage.getItem('dataTypeMap') ?? '{}')
}
const getters = {
  getMode: state => state.mode,
  getDataTypeMap: state => state.dataTypeMap
}
const mutations = {
  changeMode: (state, { mode }) => {
    state.mode = mode
    localStorage.setItem('mode', state.mode)
  },
  setRowKeyDataType: (state, { tableName, value }) => {
    const obj = state.dataTypeMap?.[tableName] ?? {}
    const newObj = Object.assign(obj, { rowKey: value })
    Vue.set(state.dataTypeMap, tableName, newObj)
    localStorage.setItem('dataTypeMap', JSON.stringify(state.dataTypeMap))
  },
  setValueDataType: (state, { tableName, family, qualifier, value }) => {
    const obj = state.dataTypeMap?.[tableName] ?? {}
    const newObj = Object.assign(obj, { [`${family}:${qualifier}`]: value })
    Vue.set(state.dataTypeMap, tableName, newObj)
    localStorage.setItem('dataTypeMap', JSON.stringify(state.dataTypeMap))
  }
}
const actions = {
  changeMode: (context, { mode }) => {
    context.commit('changeMode', { mode })
  },
  setRowKeyDataType: (context, { tableName, value }) => {
    context.commit('setRowKeyDataType', { tableName, value })
  },
  setValueDataType: (context, { tableName, family, qualifier, value }) => {
    context.commit('setValueDataType', { tableName, family, qualifier, value })
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
